/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
 * MA  02110-1301, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package system.database.mysql5;

import java.sql.Connection;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.aionemu.commons.database.DatabaseFactory;
import com.aionemu.gameserver.dao.DatabaseCleanDAO;

/**
 * @author Mr. Poke
 *
 */
public class MySQL5DatabaseCleanDAO extends DatabaseCleanDAO
{

	/** Logger */
	private static final Logger	log				= Logger.getLogger(MySQL5DatabaseCleanDAO.class);
	
	private static String[] commands = new String[5];
	static
	{
		commands[0] = "DELETE FROM players WHERE `deletion_date` < now();";
		commands[1] = "DELETE FROM `inventory` where itemOwner not in (SELECT id FROM players) and itemOwner not in (SELECT account_id FROM players) and itemOwner not in (SELECT id FROM legions);";
		commands[2] = "DELETE FROM inventory where `disappearTime` < UNIX_TIMESTAMP() and `disappearTime` != 0;";
		commands[3] = "DELETE FROM `item_cooldowns` where player_id not in (SELECT id FROM `players`);";
		commands[4] = "DELETE FROM `item_stones` where itemUniqueId not in (SELECT itemUniqueId  FROM inventory);";
	}
	/* (non-Javadoc)
	 * @see com.aionemu.commons.database.dao.DAO#supports(java.lang.String, int, int)
	 */
	@Override
	public boolean supports(String databaseName, int majorVersion, int minorVersion)
	{
		return MySQL5DAOUtils.supports(databaseName, majorVersion, minorVersion);
	}

	/* (non-Javadoc)
	 * @see com.aionemu.gameserver.dao.DatabaseCleanDAO#clean()
	 */
	@Override
	public void clean()
	{

		Connection con = null;
		int count = 0;
		try
		{
			con = DatabaseFactory.getConnection();
			Statement stmt = con.createStatement();
			for (String command : commands)
			{
				count += stmt.executeUpdate(command);
			}
			stmt.close();
			log.info("Cleaned database count: "+count);
		}
		catch (Exception e)
		{
			log.fatal("Database clean error " + e.getMessage(), e);
		}
		finally
		{
			DatabaseFactory.close(con);
		}
	}

}
